/**
 * 需求: 构建一个 HTTP 服务
 * GET  /china/mingzhu  以 ul li 标签的形式展示一下数据(服务端渲染)
 * GET  /china/mz  以 ul li 标签的形式展示一下数据(客户端渲染)
 * let data = ['西游记','红楼梦','三国演义','水浒传']
 */
let data = ["西游记", "红楼梦", "三国演义", "水浒传"];

//导入 http 模块
const http = require("http");
const urlTool = require("url");
const fs = require('fs');

//创建服务对象
const server = http.createServer((req, res) => {
  //获取请求路径
  let { method, url } = req;
  let { pathname } = urlTool.parse(url);
  //判断路径
  if(pathname === '/a/b/c' && method === 'GET'){
    //读取 app.css 文件内容
    let content = fs.readFileSync('./test/css/app.css');
    res.end(content);
  }else if (pathname === "/china/mingzhu" && method === "GET") {
    res.write(`<!DOCTYPE html>
                <html lang="en">
                <head>
                  <meta charset="UTF-8">
                  <meta name="viewport" content="width=device-width, initial-scale=1.0">
                  <title>Document</title>
                  <link rel="stylesheet" href="./a/b/c" />
                </head>
                <body>
                <h2>服务端渲染</h2>
                <ul>
                `);
    //遍历数组
    data.forEach((item) => {
      res.write(`<li>${item}</li>`);
    });
    //输出另外一半 ul
    res.write(`</ul></body>
    </html>`);
    res.end();
  } else if(pathname === '/china/mz' && method === 'GET'){
    res.end(`<!DOCTYPE html>
            <html lang="en">
            <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>四大名著</title>
              <link rel="stylesheet" href="/a/b/c" />
            </head>
            <body>
              <h2>客户端渲染</h2>
              <ul></ul>

              <script>
                //获取 ul
                let ul = document.querySelector('ul');
                //这里的数据将来可以通过 AJAX 请求获取到
                let data = ["西游记", "红楼梦", "三国演义", "水浒传"];
                //遍历 data
                data.forEach(item => {
                  //创建节点
                  let li = document.createElement('li');
                  //设置 li 的标签文本
                  li.innerHTML = item;
                  //将 li 插入到 ul 中
                  ul.append(li);
                });
              </script>
            </body>
            </html>`)
  } else{
    res.end('<h1>404 Not Found</h1>')
  }
});

//监听端口启动服务
server.listen(3000, () => {
  console.log('服务已经启动...');
})
